package io.gitee.devaper.starlight.security.config

import com.fasterxml.jackson.databind.*
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.serializer.*
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

const val SECURITY_REDIS_TEMPLATE_BEAN_NAME = "securityRedisTemplate"

@Configuration(proxyBeanMethods = false)
open class SecurityRedisConfiguration {

    @Bean(SECURITY_REDIS_TEMPLATE_BEAN_NAME)
    open fun securityRedisTemplate(
        redisConnectionFactory: RedisConnectionFactory,
        jackson2ObjectMapperBuilder: Jackson2ObjectMapperBuilder
    ): RedisTemplate<String, Any> {
        return RedisTemplate<String, Any>().apply {
            connectionFactory = redisConnectionFactory

            defaultSerializer = GenericJackson2JsonRedisSerializer(ObjectMapper().apply {
                jackson2ObjectMapperBuilder.configure(this)
            })
            keySerializer = RedisSerializer.string()
            valueSerializer = defaultSerializer!!
            hashKeySerializer = keySerializer
            hashValueSerializer = defaultSerializer!!
        }
    }

}